<template>
  <Layout title="物管巡逻" :has-back="false" :has-tabbar="true" ref="layout">
    <view
      style="
        display: flex;
        flex-direction: column;
        padding: 20rpx;
        height: 100%;
        width: 100%;
        box-sizing: border-box;
      "
    >
      <view style="flex: 1; min-height: 0">
        <map
          style="width: 100%; height: 100%"
          :longitude="location.longitude"
          :latitude="location.latitude"
          :min-scale="15"
          :enable-rotate="true"
          @regionchange="regionChange"
          :markers="markers"
          :polyline="polylines"
        ></map>
      </view>
    </view>
  </Layout>
</template>
<script>
import Layout from "@/pages/component/layout/index.vue";
import { getUuid } from "@/util/uuid";
import { getUserByAll } from "@/api/user";
import { showEditOkToast, showErrorToast } from "@/util/message";
import { createOrEditPatrol, getPatrol } from "@/api/patrol";
import { getCurrentDatetime } from "@/api/datetime";
import dayjs from "dayjs";
import isSameOrAfter from "dayjs/plugin/isSameOrAfter";
import isSameOrBefore from "dayjs/plugin/isSameOrBefore";
dayjs.extend(isSameOrAfter);
dayjs.extend(isSameOrBefore);
import _ from "lodash";
import { editOwnerByUuid } from "@/api/owner";

export default {
  components: { Layout },
  data() {
    return {
      location: {
        longitude: 0,
        latitude: 0,
      },
      selfMarkerInterval: null,
      settingOkInterval: null,
      selfMarker: {
        id: 0,
        longitude: 0,
        latitude: 0,
        iconPath: "/static/center-selected.png",
        rotate: 0,
        anchor: { x: 0.5, y: 0.5 },
        width: "40rpx",
        height: "40rpx",
      },
      selfPolyline: [],
      mapRotate: 0,
      phoneRotate: 0,
      polylineUuid: "",
      userUuid: "",
      markerAndPolyline: [],
    };
  },
  computed: {
    otherMarker() {
      return this.markerAndPolyline.map((item) => {
        return item.marker;
      });
    },
    markers() {
      return [...this.otherMarker, this.selfMarker];
    },
    polylines() {
      let selfPolyline = {
        points: this.selfPolyline,
        color: "#ff0000",
        width: 5,
        arrowLine: true,
        userUuid: this.userUuid,
      };
      let otherPolyline = this.markerAndPolyline.map((item) => {
        return item.polylines;
      });
      otherPolyline = _.flattenDeep(otherPolyline);
      return [...otherPolyline, selfPolyline];
    },
  },
  methods: {
    init() {
      // 获取定位权限
      wx.getSetting({
        success: async (res) => {
          let userLocation = res.authSetting["scope.userLocation"];
          if (userLocation === undefined) {
            wx.authorize({
              scope: "scope.userLocation",
              success: () => {
                this.settingOk();
              },
            });
          } else if (userLocation === false) {
            let result = await uni.showModal({
              title: "授权提示",
              content: "巡区功能需要定位权限，请前往设置页设置",
            });
            if (result.confirm && !result.cancel) {
              await wx.openSetting();
              this.init();
            } else {
              uni.showToast({
                title: "授权失败，功能缺失，无法定位",
                icon: "error",
              });
            }
          } else if (userLocation === true) {
            this.settingOk();
          }
        },
      });
    },
    settingOk() {
      getUserByAll()
        .then(async (result) => {
          let allUser = result.data.list;
          let user = allUser.find((user) => {
            return user.name === this.$store.state.name;
          });
          this.polylineUuid = getUuid();
          this.userUuid = user.uuid;
          await wx.startLocationUpdate({
            type: "gcj02",
          });
          this.selfMarker.longitude = 0;
          this.selfMarker.latitude = 0;
          wx.onLocationChange(this.setCurrentLocation);
          let count = 0;
          this.settingOkInterval = setInterval(() => {
            count = count + 1;
            if (count >= 5) {
              clearInterval(this.settingOkInterval);
              this.settingOkInterval = null;
              uni.showToast({
                title: "无法获取位置，请重新进入本页面",
                icon: "error",
              });
              return;
            }
            if (
              this.selfMarker.longitude === 0 ||
              this.selfMarker.latitude === 0
            ) {
              return;
            }
            clearInterval(this.settingOkInterval);
            this.settingOkInterval = null;
            this.setCenterLocation();
            this.setMarkerInterval().then(() => {
              this.selfMarkerInterval = setInterval(
                this.setMarkerInterval,
                1000
              );
              wx.startDeviceMotionListening({
                interval: "ui",
              });
              wx.onDeviceMotionChange(this.setPhoneRotate);
            });
          }, 1000);
        })
        .catch((error) => {
          showErrorToast(error);
          console.log("错误", error);
        });
    },
    setCenterLocation() {
      this.location.longitude = this.selfMarker.longitude;
      this.location.latitude = this.selfMarker.latitude;
    },
    regionChange(event) {
      let {
        type,
        detail: { rotate },
      } = event;
      if (type === "end") {
        this.mapRotate = rotate;
      }
    },
    async setPhoneRotate({ alpha, beta, gamma }) {
      this.phoneRotate = alpha;
      this.selfMarker.rotate = this.mapRotate + this.phoneRotate;
    },
    async setMarkerInterval() {
      try {
        let formData = {
          polylineUuid: this.polylineUuid,
          userUuid: this.userUuid,
          poly: {
            longitude: this.selfMarker.longitude,
            latitude: this.selfMarker.latitude,
          },
        };
        let result = await createOrEditPatrol(formData);
        this.selfPolyline = result.data;
        result = await getCurrentDatetime();
        let currentDayjs = dayjs(result.data.datetime);
        let baseDayjsStart = dayjs(currentDayjs.format("YYYY-MM-DD 07:30:00"));
        let baseDayjsEnd = dayjs(currentDayjs.format("YYYY-MM-DD 19:30:00"));
        let upEnd = dayjs(currentDayjs.format("YYYY-MM-DD 24:00:00"));
        let downStart = dayjs(currentDayjs.format("YYYY-MM-DD 00:00:00"));
        let start = "";
        let end = "";
        let isMorning =
          currentDayjs.isSameOrAfter(baseDayjsStart) &&
          currentDayjs.isBefore(baseDayjsEnd);
        if (isMorning) {
          start = currentDayjs.format("YYYY-MM-DD 07:30:00");
          end = currentDayjs.format("YYYY-MM-DD 19:29:59");
        } else {
          let isUp =
            currentDayjs.isSameOrAfter(baseDayjsEnd) &&
            currentDayjs.isSameOrBefore(upEnd);
          let isDown =
            currentDayjs.isSameOrAfter(downStart) &&
            currentDayjs.isBefore(baseDayjsStart);

          if (isUp) {
            start = currentDayjs.format("YYYY-MM-DD 19:30:30");
            end = currentDayjs.add(1, "day").format("YYYY-MM-DD 07:29:59");
          } else if (isDown) {
            start = currentDayjs
              .subtract(1, "day")
              .format("YYYY-MM-DD 19:30:30");
            end = currentDayjs.format("YYYY-MM-DD 07:29:59");
          }
        }
        result = await getPatrol({ datetimeRange: [start, end] });
        let patrolGroup = _.groupBy(result.data.list, "userUuid");
        let markerAndPolyline = [];
        let id = 0;
        for (let [userUuid, allList] of Object.entries(patrolGroup)) {
          let tempAllList = allList.map((item) => {
            return {
              ...item,
              polyline: JSON.parse(item.polyline),
            };
          });
          let color = "";
          if (userUuid === this.userUuid) {
            color = "#00ff00";
          } else {
            color = "#0000ff";
          }
          let allPolyline = [];
          for (let i = 0; i < tempAllList.length; i++) {
            let item = tempAllList[i];
            let polyline = item.polyline;
            let tempPolyline = {
              id: ++id,
              points: polyline,
              color,
              width: 5,
              arrowLine: false,
              userUuid,
            };
            if (userUuid === this.userUuid) {
              if (i < tempAllList.length - 1) {
                allPolyline.push(tempPolyline);
              }
            } else {
              allPolyline.push(tempPolyline);
            }
          }
          if (allPolyline.length === 0) {
            continue;
          }
          let points = allPolyline[allPolyline.length - 1].points;
          let longitude = points[points.length - 1].longitude;
          let latitude = points[points.length - 1].latitude;
          markerAndPolyline.push({
            polylines: allPolyline,
            marker: {
              id: ++id,
              longitude,
              latitude,
              iconPath: tempAllList[tempAllList.length - 1].avatar,
              rotate: 0,
              anchor: { x: 0.5, y: 0.5 },
              width: "40rpx",
              height: "40rpx",
              color,
              userUuid,
              name: tempAllList[tempAllList.length - 1].name,
            },
          });
        }
        let selfIndex = markerAndPolyline.findIndex((item) => {
          return item.marker.userUuid === this.userUuid;
        });
        if (selfIndex !== -1) {
          let self = markerAndPolyline.splice(selfIndex, 1);
          markerAndPolyline = [...markerAndPolyline, ...self];
        }
        this.markerAndPolyline = markerAndPolyline;
      } catch (error) {
        console.log("错误", error);
      }
    },
    async setCurrentLocation({ longitude, latitude }) {
      this.selfMarker.longitude = longitude;
      this.selfMarker.latitude = latitude;

      // this.selfMarker.longitude = longitude + 0.0005 * Math.random();
      // this.selfMarker.latitude = latitude + 0.0005 * Math.random();
    },
  },
  mounted() {
    this.$refs.layout.setTabbarStyle("物管巡逻");
    this.init();
  },
  beforeDestroy() {
    clearInterval(this.settingOkInterval);
    this.settingOkInterval = null;
    clearInterval(this.selfMarkerInterval);
    this.selfMarkerInterval = null;
    wx.offLocationChange(this.setCurrentLocation);
    wx.stopLocationUpdate();
    wx.offDeviceMotionChange(this.setPhoneRotate);
    wx.stopDeviceMotionListening();
  },
};
</script>
